<template>
  <div>
    <el-dialog :title="`${data.id?'修改':'新增'}学科`" :visible.sync="showModal" width="35%">
      <el-form label-width="120px" ref="form" :model="formModel" :rules="rules">
        <el-form-item label="学科名称" prop="subjectName">
          <el-input v-model="formModel.subjectName" placeholder="请输入学科名称"></el-input>
        </el-form-item>
        <el-form-item label="是否显示" prop="isFrontDisplay">
          <el-switch
            v-model="formModel.isFrontDisplay"
            active-color="#13ce66"
            inactive-color="#ff4949"
            :active-value="1"
            :inactive-value="0"
          ></el-switch>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="closeModal">取 消</el-button>
        <el-button type="primary" @click="confirm">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
import { add, update } from '@/api/hmmm/subjects'
export default {
  props: {
    data: {
      default: () => {},
      type: Object
    }
  },
  data () {
    return {
      showModal: false,
      // switchStatus: true, // switch的状态
      formModel: {
        id: null,
        subjectName: null,
        isFrontDisplay: 1
      },
      rules: {
        subjectName: [
          { required: true, message: '请输入学科名称', tirgger: 'blur' }
        ]

      }
    }
  },
  methods: {
    submitForm () {
      this.showModal = true
    },
    // 打开弹出框
    openModal () {
      this.showModal = true
      if (this.data.id) {
        const { id, subjectName, isFrontDisplay } = this.data
        this.formModel = { id, subjectName, isFrontDisplay }
      } else {
        this.formModel = {
          id: null,
          subjectName: null,
          isFrontDisplay: 1
        }
        // console.log(111)
      }
      // 清除校验效果
      this.$nextTick(() => {
        this.$refs.form.clearValidate()
      })
    },
    // 关闭弹出框
    closeModal () {
      this.showModal = false
    },
    // 点击确认按钮时执行的操作
    async  confirm () {
      // TODO: 在这里添加确认操作
      // 关闭弹出框
      // this.showModal = false
      this.$refs.form.validate(async valid => {
        if (valid) {
          // 提交
          if (!this.data.id) {
            // 新增
            await add(this.formModel)
          } else {
            // 修改
            this.formModel.id = this.data.id
            await update(this.formModel)
          }
          this.$message.success('操作成功')
          this.showModal = false
          this.$emit('updateList')
        }
      })
    }
  }
}
</script>
